package registration.adventurezone.thevine.com;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class ChildArrayAdapter extends ArrayAdapter<ChildViewHolder> {
	private LayoutInflater inflater;
	private int layout;
	
	public ChildArrayAdapter(Context context, List<ChildViewHolder> childrenList, int resource) {
		super(context, resource, R.id.itemTextView, childrenList);
		this.inflater = LayoutInflater.from(context);
		this.layout = resource;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if(layout == R.layout.simplerow) {
			ChildViewHolder child = (ChildViewHolder) this.getItem(position);			
			CheckBox checkBox;
			TextView textView;
			
			if(convertView == null) {
				convertView = inflater.inflate(R.layout.simplerow, null);
				textView = (TextView) convertView.findViewById(R.id.rowTextView);
				checkBox = (CheckBox) convertView.findViewById(R.id.isCheckedIn);
				//Optimization: Tag the row with it's child views, so we don't have to
				//call findViewById() later when we reuse the row.
				convertView.setTag(new ChildViewHolder(child.getDBChild(), textView, checkBox));
				
				checkBox.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						CheckBox cb = (CheckBox) v;
						ChildViewHolder child = (ChildViewHolder) cb.getTag();
						child.setChecked(cb.isChecked());
					}
				});
			}
			else {
				ChildViewHolder viewHolder = (ChildViewHolder) convertView.getTag();
				checkBox = viewHolder.getCheckBox();
				textView = viewHolder.getTextView();
			}
			
			checkBox.setTag(child);
			checkBox.setChecked(child.isChecked());
			textView.setText(child.getName());
			return convertView;
		}
		else {
			ChildViewHolder child = (ChildViewHolder) this.getItem(position);
			
			TextView textView;
		
			if(convertView == null) {
				convertView = inflater.inflate(R.layout.simple_list_row, null);
			}
			textView = (TextView) convertView.findViewById(R.id.itemTextView);
			textView.setText(child.getName());
			
			return convertView;
		}
		
	}
	
}

